import { defineStore } from 'pinia';

import { Notification } from '@arco-design/web-vue';
import type { RouteRecordRaw, RouteMeta } from 'vue-router';
import type { NotificationReturn } from '@arco-design/web-vue/es/notification/interface';

import { CONSTANT_ROUTES } from '@/router';
import { DEFAULT_LAYOUT } from '@/router/routes/base';
import defaultSettings from '@/config/settings.json';
import { getMenuList } from '@/api/sys/user';
import { AppState } from './types';

const modules = import.meta.glob('@/views/**/*.vue')


const useAppStore = defineStore('app', {
  state: (): AppState => ({ ...defaultSettings }),

  getters: {
    appCurrentSetting(state: AppState): AppState {
      return { ...state };
    },
    appDevice(state: AppState) {
      return state.device;
    },
    appAsyncMenus(state: AppState): RouteRecordRaw[] {
      return state.serverMenu as unknown as RouteRecordRaw[];
    },
    appAddRoute(state: AppState) {
      return state.isAddRoute;
    },
  },

  actions: {
    // Update app settings
    updateSettings(partial: Partial<AppState>) {
      // @ts-ignore-next-line
      this.$patch(partial);
    },

    // Change theme color
    toggleTheme(dark: boolean) {
      if (dark) {
        this.theme = 'dark';
        document.body.setAttribute('arco-theme', 'dark');
      } else {
        this.theme = 'light';
        document.body.removeAttribute('arco-theme');
      }
    },
    toggleDevice(device: string) {
      this.device = device;
    },
    toggleMenu(value: boolean) {
      this.hideMenu = value;
    },
    setAddRoute(value: boolean) {
      this.isAddRoute = value;
    },
    // 获取服务端菜单信息
    async fetchServerMenuConfig() {
      let notifyInstance: NotificationReturn | null = null;
      try {
        notifyInstance = Notification.info({
          id: 'menuNotice', // Keep the instance id the same
          content: 'loading',
          closable: true,
        });
        const { data } = await getMenuList();
        if (!data) {
          return;
        }
        this.filterServerMenu(data);
        notifyInstance = Notification.success({
          id: 'menuNotice',
          content: 'success',
          closable: true,
        });
      } catch (error) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        notifyInstance = Notification.error({
          id: 'menuNotice',
          content: 'error',
          closable: true,
        });
      }
    },
    clearServerMenu() {
      this.serverMenu = [];
      this.setAddRoute(false);
    },
    // 处理后端返回菜单
    filterServerMenu(data: ServerMenu[]) {
      const serverMenus: RouteRecordRaw[] = [];
      data.forEach(item => {
        const routeMeta: RouteMeta = {
          title: item.meta.title,
          icon: item.meta.icon,
          requiresAuth: true,
          hideInMenu: item.hidden
        }
        const route: RouteRecordRaw = {
          name: item.name,
          path: item.path,
          component : {},
          props: {},
          meta: routeMeta,
        };
        if (item.component === 'ParentView' || item.component === 'InnerLink') {
          route.component = {}
        } else {
          route.component = item.component === 'Layout' ? DEFAULT_LAYOUT : modules[`/src/views/${item.component}.vue`];
        }
        // Layout 组件特殊处理
        if (item.children && item.children.length > 0) {
          this.filterServerChildrenMenu(route, item.children);
        }
        serverMenus.push(route)
      })
      this.serverMenu = CONSTANT_ROUTES.concat(serverMenus);
    },
    // 处理子菜单
    filterServerChildrenMenu(paretnRoute: RouteRecordRaw, serverMenus: ServerMenu[]) {
      const childServerMenus: RouteRecordRaw[] = [];
      serverMenus.forEach(item => {
        const routeMeta: RouteMeta = {
          title: item.meta.title,
          icon: item.meta.icon,
          requiresAuth: true,
          hideInMenu: item.hidden
        }
        const route: RouteRecordRaw = {
          name: item.name,
          path: `${paretnRoute.path}/${item.path}`,
          component : {},
          props: {},
          meta: routeMeta,
        };
        if (item.redirect === 'ParentView' || item.redirect === 'InnerLink') {
          route.component = {}
        } else {
          route.component = item.redirect === 'Layout' ? DEFAULT_LAYOUT : modules[`/src/views/${item.component}.vue`];
        }
        if (item.children && item.children.length > 0) {
          this.filterServerChildrenMenu(route, item.children);
        }
        childServerMenus.push(route);
      })
      paretnRoute.children = childServerMenus;
    },
  },
});

export default useAppStore;
